package com.manager.gen.module;

import com.manager.core.shiro.config.ShiroConfig;
import com.manager.core.shiro.config.ShiroUtil;
import com.manager.core.shiro.core.entity.ShiroRolePermission;
import com.manager.core.shiro.core.service.ShiroService;
import com.manager.gen.web.controller.AdminController;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 控制器
 *
 * @author H
 * @version 1.0
 */
@Controller
public class MainController extends AdminController<String> {
    @Autowired
    private ShiroService _service;

    /**
     * 欢迎页
     *
     * @return
     */
    @RequestMapping("/welcome")
    public ModelAndView welcome() {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {
            return getModelAndView("login");
        }
        request.setAttribute("menus", getMenus());
        return getModelAndView("center");
    }


    /**
     * 欢迎页
     *
     * @return
     */
    @RequestMapping("/center")
    public ModelAndView center() {
        request.setAttribute("menus", getMenus());
        request.setAttribute("name", getUserSession().getUserName());
        request.setAttribute("roleName", ShiroUtil.getCurrentRoleName());
        return getModelAndView("center");
    }

    /**
     * 首页
     *
     * @return
     */
    @RequestMapping("/login")
    public ModelAndView login() {
        return getModelAndView("login");
    }

    /**
     * 首页
     *
     * @return
     */
    @RequestMapping("/home")
    public ModelAndView home() {
        return getModelAndView("home");
    }

    /**
     * 首页
     *
     * @return
     */
    @RequestMapping("/logout")
    public ModelAndView logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        getSession().invalidate();
        return getModelAndView("login");
    }

    private List<ShiroRolePermission> getMenus() {
        String role = ShiroUtil.getCurrentRole();
        if (role.equals(ShiroConfig.superAdmin)) {
            return _service.queryPermissionsAllThree();
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("roleCode", role);
            return _service.queryPermissionThree(map);
        }
    }

    @Override
    public String getModel() {
        return null;
    }
}